package com.personal.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import com.google.gson.Gson;
import com.personal.book.commons.AjaxResponse;
import com.personal.book.dao.BookDao;
import com.personal.book.dao.BookTypeDao;
import com.personal.book.dao.FileDao;
import com.personal.book.dao.impl.BookDaoImpl;
import com.personal.book.dao.impl.BookTypeDaoImpl;
import com.personal.book.entity.Book;
import com.personal.book.entity.BookType;
import com.personal.book.service.BookService;
import com.personal.book.service.BookTypeService;
import com.personal.book.service.impl.BookServiceImpl;
import com.personal.book.service.impl.BookTypeServiceImpl;
import com.personal.tools.PageData;

/**
 * Servlet implementation class BookServlet
 */
@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	BookService bookService = new BookServiceImpl();
	BookDao bookDao = new BookDaoImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BookServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		BookService service = new BookServiceImpl();
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("".equals(op)) {
			doquery(request, response, service);

		} else if ("add".equals(op)) {
			List<String> list = new ArrayList<String>();
			String filename = FileDao.getPhotoNewName();
			ServletContext servletContext = null;
			servletContext = request.getSession().getServletContext();
			// 数据库中存储格式:/webTest/imgs/***.jpg
			// 第一步:获取页面上上传的图片资源
			List<FileItem> items = FileDao.getRequsetFileItems(request, servletContext);
			boolean isLoadToSQL = false;
			for (FileItem item : items) {
				if (!item.isFormField()) {
					// 判断后缀名是否是jpg
					if (FileDao.isGif(item)) {
						isLoadToSQL = FileDao.saveFile(item, filename);
						String path = request.getContextPath() + "/WebContent/images/" + filename;
						System.out.println(path);
						// request.setAttribute("path", path);
						// request.getRequestDispatcher("look.jsp").forward(request, response);
					} else {
						System.out.println("后缀格式有误，保存文件失败");
					}
				} else {
					String paramName = item.getFieldName();
					String paramValue = item.getString();

					// //乱码问题
					paramValue = new String(paramValue.getBytes("iso8859-1"), "utf-8");
					list.add(paramValue);
					System.out.println(paramName + " = " + paramValue);
				}
			}
			Book book = new Book(list.get(0), list.get(1), filename, list.get(2), list.get(3),
					Double.parseDouble(list.get(4)), Integer.parseInt(list.get(5)), list.get(6));
			if (service.addBookInfo(book)) {
				System.out.println("添加成功");
				doquery(request, response, service);
			} else {
				System.out.println("添加失败");
			}
		} else if ("del".equals(op)) {
			// 1.设置响应头的contentType
			response.setContentType("application/json;charset=utf-8");

			// 先获取请求参数的值
			int bookId = 0;

			if (request.getParameter("bookId") != null) {
				bookId = Integer.parseInt(request.getParameter("bookId"));
			}

			// 2 调用 service的方法
			boolean flag = service.delBookInfo(bookId);

			AjaxResponse res = new AjaxResponse(flag + "", 200);
			// 3将list转换为json格式的字符串
			Gson gson = new Gson();
			String jsonString = gson.toJson(res);

			// 4 响应
			PrintWriter outPrintWriter = response.getWriter();
			outPrintWriter.print(jsonString);

			// 5.关闭
			outPrintWriter.close();
		} else if ("queryById".equals(op)) {
			doquerybyid(request, response, service);
		} else if ("update".equals(op)) {
			updatebook(request, response, service);
		} else if ("search".equals(op)) {
			doSearch(request, response);
		}

	}

	/**
	 * 根据书名模糊查询
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doSearch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String search = request.getParameter("search");
		List<Book> list = bookService.getInfoByKey(search);

		request.setAttribute("list", list);
		request.getRequestDispatcher("shop.jsp").forward(request, response);
	}

	/**
	 * 修改
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatebook(HttpServletRequest request, HttpServletResponse response, BookService service)
			throws ServletException, IOException {
		List<String> list = new ArrayList<String>();
		String filename = FileDao.getPhotoNewName();
		ServletContext servletContext = null;
		servletContext = request.getSession().getServletContext();
		// 数据库中存储格式:/webTest/imgs/***.jpg
		// 第一步:获取页面上上传的图片资源
		List<FileItem> items = FileDao.getRequsetFileItems(request, servletContext);
		boolean isLoadToSQL = false;
		for (FileItem item : items) {
			if (!item.isFormField()) {
				// 判断后缀名是否是jpg
				if (FileDao.isGif(item)) {
					isLoadToSQL = FileDao.saveFile(item, filename);
					String path = request.getContextPath() + "/WebContent/images/" + filename;
					System.out.println(path);
					// request.setAttribute("path", path);
					// request.getRequestDispatcher("look.jsp").forward(request, response);
				} else {
					System.out.println("后缀格式有误，保存文件失败");
				}
			} else {
				String paramName = item.getFieldName();
				String paramValue = item.getString();

				// //乱码问题
				paramValue = new String(paramValue.getBytes("iso8859-1"), "utf-8");
				list.add(paramValue);
				System.out.println(paramName + " = " + paramValue);
			}
		}
		Book book = new Book(Integer.parseInt(list.get(0)), list.get(1), list.get(2), filename, list.get(3), list.get(4),
				Double.parseDouble(list.get(5)), Integer.parseInt(list.get(6)), list.get(7));
		if (service.updateBookInfo(book)) {
			System.out.println("修改成功");
			doquery(request, response, service);
		} else {
			System.out.println("修改失败");
		}
	}

	/**
	 * 按编号查询
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doquerybyid(HttpServletRequest request, HttpServletResponse response, BookService service)
			throws ServletException, IOException {
		int bookId = Integer.parseInt(request.getParameter("bookId"));

		Book book = bookService.getInfoById(bookId);

		request.setAttribute("book", book);

		request.getRequestDispatcher("updateBookInfo.jsp").forward(request, response);
	}

	private void doquery(HttpServletRequest request, HttpServletResponse response, BookService service)
			throws ServletException, IOException {
		String key = "";
		if (request.getParameter("keyname") != null) {
			key = request.getParameter("keyname");
		}
		int page = 1;
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		PageData<Book> pd = service.getInfoByPage(page, pageSize, key + "%");
		request.setAttribute("pd", pd);
		request.setAttribute("key", key);
		request.getRequestDispatcher("bookInfo.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
